package com.computergames.server.service.Implement;

import com.computergames.server.domain.ClientState;
import com.computergames.server.message.ErrorResponseMessage;
import com.computergames.server.service.Interface.CheckAndUpdateClientState;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class CheckAndUpdateClientStateImpl implements CheckAndUpdateClientState {
    private final Map<Channel, ClientState> clientStates = new ConcurrentHashMap<>();
    @Override
    public boolean checkState(ChannelHandlerContext ctx, ClientState requiredState) {
        ClientState currentState = clientStates.get(ctx.channel());
        if (currentState != requiredState) {
            log.error("Invalid state for message: {}. Current state is {}.", requiredState, currentState);
            return false;
        }
        return true;
    }

    @Override
    public void updateState(Channel channel, ClientState newState) {
        clientStates.put(channel, newState);
    }

    @Override
    public void removeState(Channel channel) {
        clientStates.remove(channel);
    }

    @Override
    public ClientState getState(Channel channel) {
        return clientStates.get(channel);
    }


}
